const chooseLocation = requirePlugin('chooseLocation');
Page({
  data: {
    id: null, // 编辑模式下的地址ID
    isEdit: false, // 是否为编辑模式
    addressForm: {
      consignee: '', // 收货人姓名
      phone: '', // 手机号码
      address: '', // 完整地址（地图地址+详细地址）
      detailAddress: '', // 用户手动输入的详细地址
      province: '', // 省份
      city: '', // 城市
      district: '', // 区县
      latitude: 39.89631551, // 纬度
      longitude: 116.323459711, // 经度
      isDefault: 0 // 是否默认地址
    },
    showMap: false // 是否显示地图选择器
  },

  onLoad(query) {
    const { id } = query;
    if (id) {
      this.setData({ 
        id,
        isEdit: true 
      });
      this.loadAddressDetail(id);
    }
  },

  // 加载地址详情（编辑模式）
  loadAddressDetail(id) {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.request({
      url: `http://localhost:8080/point/address/${id}`,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const addressData = res.data.data;
          
          // 尝试从完整地址中提取详细地址
          let detailAddress = '';
          if (addressData.address) {
            // 如果有省市区信息，尝试提取详细地址
            if (addressData.province && addressData.city && addressData.district) {
              const baseAddress = addressData.province + addressData.city + addressData.district;
              if (addressData.address.startsWith(baseAddress)) {
                detailAddress = addressData.address.substring(baseAddress.length).trim();
              } else {
                detailAddress = addressData.address;
              }
            } else {
              detailAddress = addressData.address;
            }
          }
          
          this.setData({
            addressForm: {
              consignee: addressData.consignee || '',
              phone: addressData.phone || '',
              address: addressData.address || '',
              detailAddress: detailAddress,
              province: addressData.province || '',
              city: addressData.city || '',
              district: addressData.district || '',
              latitude: addressData.latitude || 39.89631551,
              longitude: addressData.longitude || 116.323459711,
              isDefault: addressData.isDefault || 0
            }
          });
        }
      },
      fail: (err) => {
        console.error('获取地址详情失败', err);
        wx.showToast({
          title: '获取地址详情失败',
          icon: 'none'
        });
      }
    });
  },

  // 输入收货人姓名
  onConsigneeInput(e) {
    this.setData({
      'addressForm.consignee': e.detail.value
    });
  },

  // 输入手机号码
  onPhoneInput(e) {
    this.setData({
      'addressForm.phone': e.detail.value
    });
  },

  // 输入详细地址
  onAddressInput(e) {
    const detailAddress = e.detail.value;
    this.setData({
      'addressForm.detailAddress': detailAddress
    });
    
    // 重新组合完整地址
    this.updateFullAddress();
  },

  // 更新完整地址
  updateFullAddress() {
    const { province, city, district, detailAddress } = this.data.addressForm;
    
    // 组合完整地址：省市区 + 详细地址
    let fullAddress = '';
    if (province && city && district) {
      fullAddress = province + city + district;
    }
    
    if (detailAddress && detailAddress.trim()) {
      fullAddress = fullAddress + ' ' + detailAddress.trim();
    }
    
    this.setData({
      'addressForm.address': fullAddress
    });
  },

  // 切换默认地址
  onToggleDefault(e) {
    const isDefault = e.detail.value;
    
    this.setData({
      'addressForm.isDefault': isDefault ? 1 : 0
    });
  },

  // 清除其他默认地址
  clearOtherDefaultAddresses() {
    const userId = getApp().globalData.userInfo?.id || getApp().globalData.userInfo1?.id;
    if (!userId) {
      console.error('用户ID不存在');
      return;
    }

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      return;
    }

    wx.request({
      url: 'http://localhost:8080/point/address/clear-default',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: { userId },
      success: (res) => {
        if (res.data.code === 200) {
          console.log('清除其他默认地址成功');
        } else {
          console.error('清除其他默认地址失败:', res.data.msg);
        }
      },
      fail: (err) => {
        console.error('清除其他默认地址失败', err);
      }
    });
  },

  // 更新全局默认地址状态
  updateGlobalDefaultAddress(addressData) {
    const app = getApp();
    
    // 更新全局默认地址信息
    if (app.globalData.defaultAddress) {
      app.globalData.defaultAddress = addressData;
    }
    
    // 通知上一页刷新地址列表
    const pages = getCurrentPages();
    if (pages.length > 1) {
      const prevPage = pages[pages.length - 2];
      if (prevPage && prevPage.loadAddressList) {
        prevPage.loadAddressList();
      }
    }
  },

  // 选择地图位置
  onChooseLocation() {
    const key = '32CBZ-QGF67-4RMXG-PJ7HA-QAVHF-VJBR6'; // 使用在腾讯位置服务申请的key
    const referer = 'asd'; // 调用插件的app的名称
    const location = JSON.stringify({
      latitude: this.data.addressForm.latitude,
      longitude: this.data.addressForm.longitude,
    });
    const category = '生活服务,娱乐休闲';

    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`,
    });
  },

  // 页面显示时处理地图选择结果
  onShow() {
    const location = chooseLocation.getLocation(); 
    console.log("123",location);
    // 获取地图选择结果
    if (location) {
      const { name, address, latitude, longitude, province, city, district } = location;
      
      // 使用地图返回的address作为基础地址
      let baseAddress = address || '';
      
      // 如果有name，可以添加到地址前面
      if (name && name !== address) {
        baseAddress = name + ' ' + baseAddress;
      }
      
      // 获取用户之前输入的详细地址
      const userDetailAddress = this.data.addressForm.detailAddress || '';
      
      // 组合完整地址：地图地址 + 用户详细地址
      let fullAddress = baseAddress;
      if (userDetailAddress.trim()) {
        fullAddress = baseAddress + ' ' + userDetailAddress.trim();
      }
      
      this.setData({
        'addressForm.address': fullAddress,
        'addressForm.province': province || '',
        'addressForm.city': city || '',
        'addressForm.district': district || '',
        'addressForm.latitude': latitude || 39.89631551,
        'addressForm.longitude': longitude || 116.323459711
      });
      
      // 清除存储的选择结果
      wx.removeStorageSync('chooseLocationRes');
    }
  },

  // 验证表单
  validateForm() {
    const { consignee, phone, address } = this.data.addressForm;
    
    if (!consignee.trim()) {
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      });
      return false;
    }
    
    if (!phone.trim()) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      });
      return false;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      return false;
    }
    
    if (!address.trim()) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  },

  // 保存地址
  onSaveAddress() {
    if (!this.validateForm()) {
      return;
    }

    const { id, isEdit, addressForm } = this.data;
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    console.log('准备保存/更新地址:', {
      isEdit,
      id,
      addressForm,
      token: token ? '已获取' : '未获取'
    });

    wx.showLoading({
      title: isEdit ? '更新中...' : '保存中...',
      mask: true
    });

    const requestData = {
      ...addressForm,
      userId: getApp().globalData.userInfo?.id || getApp().globalData.userInfo1?.id,
      operationType: isEdit ? 'update' : 'create' // 添加操作类型标识
    };

    // 如果设置为默认地址，先清除其他默认地址
    if (addressForm.isDefault === 1) {
      this.clearOtherDefaultAddresses();
    }

    const url = isEdit 
      ? `http://localhost:8080/point/address/update/${id}`
      : 'http://localhost:8080/point/address';
    
    const method = 'POST'; // 统一使用POST方法

    console.log('发送请求:', {
      url,
      method,
      requestData
    });

    wx.request({
      url: url,
      method: method,
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: requestData,
      success: (res) => {
        wx.hideLoading();
        console.log('地址保存/更新响应:', res.data);
        
        if (res.data.code === 200) {
          wx.showToast({
            title: isEdit ? '更新成功' : '保存成功',
            icon: 'success'
          });
          
          // 如果设置为默认地址，更新全局状态
          if (addressForm.isDefault === 1) {
            this.updateGlobalDefaultAddress(res.data.data);
          }
          
          // 返回上一页并刷新地址列表
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          console.error('地址保存/更新失败:', res.data);
          wx.showToast({
            title: res.data.msg || (isEdit ? '更新失败' : '保存失败'),
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('地址保存/更新请求失败:', err);
        
        // 提供更详细的错误信息
        let errorMsg = '保存失败，请重试';
        if (err.errMsg) {
          if (err.errMsg.includes('PUT')) {
            errorMsg = '请求方法不支持，请联系管理员';
          } else if (err.errMsg.includes('timeout')) {
            errorMsg = '请求超时，请检查网络';
          } else if (err.errMsg.includes('fail')) {
            errorMsg = '网络请求失败，请检查网络连接';
          }
        }
        
        wx.showToast({
          title: errorMsg,
          icon: 'none'
        });
      }
    });
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  }
}); 